@using System.Web.Optimization
@using VocaDb.Model.DataContracts.Artists;
@using VocaDb.Model.Domain
@using VocaDb.Model.Domain.Artists
@using VocaDb.Model.Domain.Images
@using VocaDb.Model.Service
@using VocaDb.Model.Utils
@using VocaDb.Web.Helpers;
@using VocaDb.Model.Domain.Security
@using VocaDb.Model.Service.QueryableExtenders
@using VocaDb.Web.Models.Search
@using VocaDb.Web.Models.Shared
@using R = ViewRes.Artist;
@using Res = ViewRes.Artist.DetailsStrings
@inherits VocaDb.Web.Code.VocaDbPage<ArtistDetailsContract>

@{
	ViewBag.Parents = new[] { Html.ActionLink(ViewRes.SharedStrings.Artists, "Index") };
	var url = PageProperties.CanonicalUrl;
}

@section Head {
	@HtmlHelpers.OpenGraphMetaTags(PageProperties)
	<link rel="canonical" href="@url" />
	<link rel="stylesheet" href="@Url.Content("~/Content/Styles/songlist.css")" type="text/css" />
}

@section Toolbar {
	<a href="#" id="addToUserLink" class="@(Login.Manager.IsLoggedIn ? "" : "disabled")" data-bind="visible: !hasArtistSubscription(), click: addFollowedArtist">@ViewRes.Artist.DetailsStrings.Follow</a>
	<span id="removeFromUserSplitBtn" data-bind="visible: hasArtistSubscription">
		<a href="#" id="removeFromUserLink" class="@(Login.Manager.IsLoggedIn ? "" : "disabled")" data-bind="click: removeFollowedArtist">@ViewRes.Artist.DetailsStrings.Unfollow</a>
		<a data-bind="click: customizeSubscriptionDialog.show" href="#" id="customizeSubscription">@R.DetailsStrings.Customize</a>
	</span>

	@Html.ActionLink(ViewRes.SharedStrings.Edit, "Edit", new { id = Model.Id }, new { id = "editArtistLink", @class = (Login.CanEdit(Model) ? "" : "disabled") })

	@Html.ActionLink(ViewRes.EntryDetailsStrings.ViewModifications, "Versions", new { id = Model.Id }, new { id = "viewVersions" })

	<a href="#" id="reportEntryLink" data-bind="click: reportViewModel.show">@ViewRes.EntryDetailsStrings.ReportAnError</a>

	@Helpers.EntryStatusMessage(Model.Status)
}

@helper DataRow(string label, HelperResult content) {
	if (content != null) {
		<tr>
			<td>@label</td>
			<td>@content</td>
		</tr>
	}
}

@helper ArtistListRow(string label, ArtistContract[] artists, bool typeLabel, bool releaseYear = false) {
	@DataRow(label, artists.Any() ? ArtistHelpers.ArtistLinkList(artists, typeLabel: typeLabel, releaseYear: releaseYear) : null)
}

@helper ArtistRow(string label, ArtistContract artist, bool typeLabel) {
	@DataRow(label, artist != null ? ArtistHelpers.ArtistLink(artist, typeLabel: typeLabel) : null)
}

@if (Model.Deleted) {
	@EntryDetailsHelpers.DeletedBanner(Model.MergedTo)
}

@if (Model.Draft && !Model.Deleted) {
	@Helpers.DraftMessage("glproducers")
}

<div id="tabs" class="artist-details-page js-cloak" data-bind="show">

	<ul>
		<li><a href="#basicInfoTab">@ViewRes.EntryDetailsStrings.BasicInfoTab</a></li>
		<li data-tab="Discussion">
			<a href="#discussionTab">@ViewRes.EntryDetailsStrings.DiscussionTab (@Model.CommentCount)</a>
		</li>
		<li><a href="#picturesTab">@ViewRes.EntryDetailsStrings.PicturesTab (@(Model.Pictures.Length + 1))</a></li>
		<li>
			<a href="#mainAlbumsTab" data-bind="click: initMainAlbums">
				<span>@R.DetailsStrings.MainAlbums</span>
			</a>
		</li>
		<li>
			<a href="#collaborationAlbumsTab" data-bind="click: initCollaborationAlbums">
				<span>@R.DetailsStrings.CollaborationAlbums</span>
			</a>
		</li>
		<li><a href="#songsTab" data-bind="click: initSongs"><span>@ViewRes.Artist.DetailsStrings.AllSongs</span></a></li>
		<li><a href="#shareTab">@R.DetailsStrings.Share</a></li>
	</ul>

	<div id="basicInfoTab">

		<div class="clearfix">
			<!-- Artist picture -->
			<div class="pull-left entry-main-picture">
				<a href="@Url.Action("Picture", new { id = Model.Id, v = Model.Version })">
					<img src="@Url.ImageThumb(Model, VocaDb.Model.Domain.Images.ImageSize.Thumb)" alt="@ViewRes.Artist.DetailsStrings.ArtistPicture" class="coverPic" />
				</a>
			</div>

			<table class="properties">
				<tr>
					<td class="entry-field-label-col">@ViewRes.SharedStrings.ArtistName</td>
					<td>
						@Model.Name<br />
						<span class="extraInfo">@Model.AdditionalNames</span>
					</td>
				</tr>
				@if (!Model.Description.IsEmpty) {
					<tr>
						<td>@ViewRes.SharedStrings.Description</td>
						<td class="entry-description" data-bind="with: description">
							@{ Html.RenderPartial("Partials/_EnglishTranslatedString", new EnglishTranslatedStringViewModel(Model.Description)); }
						</td>
					</tr>
				}
						
				@if (Model.ReleaseDate.HasValue) {
				<tr>
					<td>@Res.ReleaseDate</td>
					<td>
						@Model.ReleaseDate.Value.ToShortDateString()
					</td>
				</tr>				
				}
									
				@ArtistListRow(Res.Illustrator, Model.Illustrators, false)
				@ArtistListRow(Res.IllustratorOf, Model.IllustratorOf, true, releaseYear: true)
				@ArtistListRow(Res.VoiceProvider, Model.VoiceProviders, false)
				@ArtistListRow(Res.VoiceProviderOf, Model.Voicebanks, true, releaseYear: true)
				@ArtistRow(Res.ManagedBy, Model.Manager, false)
				@ArtistRow(Res.CharacterDesigner, Model.CharacterDesigner, false)
				@ArtistListRow(Res.CharacterDesignerOf, Model.CharacterDesignerOf, typeLabel: true)

				<tr>
					<td>@ViewRes.SharedStrings.Type</td>
					<td>
						@ArtistHelpers.ArtistTypeLabel(Model.ArtistType)
						@Html.ActionLink(Translate.ArtistTypeName(Model.ArtistType), "Index", new { artistType = Model.ArtistType })<br />
					</td>
				</tr>

				<tr>
					<td>@ViewRes.SharedStrings.Tags</td>
					<td>
						<div data-bind="with: tagUsages" class="entry-tag-usages">
							@{ Html.RenderPartial("Partials/_TagList"); }
						</div>
						<a data-bind="jqButton: { disabled: @ToJS(!Login.CanEditTags), icon: 'ui-icon-tag' }, click: tagsEditViewModel.show" href="#">@ViewRes.EntryDetailsStrings.EditTags</a>
						@if (Model.CanRemoveTagUsages) {
							@Html.ActionLink(ViewRes.EntryDetailsStrings.ManageTags, "ManageTagUsages", new { id = Model.Id }, new { id = "manageTags" })
						}
					</td>
				</tr>

				@EntryDetailsHelpers.ExternalLinksRows(Model.WebLinks)

				@if (Model.OwnerUsers.Any()) {
					<tr>
						<td>
							@BrandableStrings.Artist.AuthoredBy
						</td>
						<td>
							@foreach (var user in Model.OwnerUsers) {
								@UserHelpers.UserIconLink(user, tooltip: true)
								<br />
							}
						</td>
					</tr>
				}
				
				@if (Model.BaseVoicebank != null) {
					<tr>
						<td>
							<span>
								@Res.BaseVoicebank
							</span>
						</td>
						<td id="baseVoicebank">
							@ArtistHelpers.ArtistLink(Model.BaseVoicebank, releaseYear: true)
						</td>
					</tr>
				}

				@if (Model.ChildVoicebanks.Any()) {
					<tr>
						<td>
							<span>
								@Res.ChildVoicebanks
							</span>
						</td>
						<td id="childVoicebanks">
							@foreach (var a in Model.ChildVoicebanks) {
								@ArtistHelpers.ArtistLink(a, releaseYear: true)
								if (a != Model.ChildVoicebanks.Last()) {
									@(", ")
								}
							}
						</td>
					</tr>
				}

				@if (Model.Groups.Any()) {
					<tr>
						<td>
							<span title="@Res.GroupsHelp">
								@Res.Groups
							</span>
						</td>
						<td id="groups">
							@foreach (var grp in Model.Groups) {
								@ArtistHelpers.ArtistLink(grp)
								if (grp != Model.Groups.Last()) {
									@(", ")
								}
							}
						</td>
					</tr>
				}

				<tr>
					<td>@ViewRes.EntryDetailsStrings.Stats</td>
					<td>
						@string.Format(Res.FollowCount, Model.SharedStats.FollowerCount)
						@if (Model.SharedStats.RatedSongCount > 0) {
							@:@string.Format(Res.RatedSongs, Model.SharedStats.RatedSongCount)
						}
						@if (Model.SharedStats.RatedAlbumCount > 0) {
							@:@string.Format(Res.RatedAlbums, Model.SharedStats.RatedAlbumCount)
							@:@string.Format(Res.AverageAlbumRating, Model.SharedStats.AlbumRatingAverage)
						}
						@if (Model.PersonalStats != null && Model.PersonalStats.SongRatingCount > 0) {
							<a href="@Url.Action("Profile", "User", new { id = UserContext.LoggedUser.Name, artistId = Model.Id })#Songs">@string.Format(Res.YouHaveRatedSongs, Model.PersonalStats.SongRatingCount)</a>
						}
						@if (Model.AdvancedStats != null && Model.AdvancedStats.TopVocaloids.Any()) {
							<p>
								@Res.MostlyUses @ArtistHelpers.ArtistLinkList(Model.AdvancedStats.TopVocaloids.Select(a => a.Data), typeLabel: true).
							</p>
						}
					</td>
				</tr>

				<tr>
					<td>@ViewRes.EntryDetailsStrings.AdditionDate</td>
					<td>
						@Helpers.UniversalTimeLabel(Model.CreateDate)
					</td>
				</tr>

			</table>
		</div>

		@if (Model.Members.Any()) {
			<h3>
				@Res.Members
				<small>(@string.Format(ViewRes.EntryDetailsStrings.NumTotal, Model.Members.Length))</small>
			</h3>
			<div data-bind="visible: !showAllMembers()">
				@ArtistHelpers.ArtistGrid(Model.Members.Take(6).Select(g => g), 3, true)
			</div>
			if (Model.Members.Length > 6) {
				<div data-bind="visible: showAllMembers">
					@ArtistHelpers.ArtistGrid(Model.Members.Select(g => g), 3, true)
				</div>
				<a href="#" data-bind="click: function() { showAllMembers(true); }, visible: !showAllMembers()">@ViewRes.SharedStrings.ShowMore</a>
			}
		}

		@if (Model.LatestAlbums.Any()) {
			<h3 class="withMargin">
				@Html.ActionLink(Res.RecentAlbums, "Index", "Search", new { searchType = EntryType.Album, artistId = Model.Id, sort = AlbumSortRule.AdditionDate }, null)
				<small>@string.Format(ViewRes.EntryDetailsStrings.NumTotalParenthesis, Model.SharedStats.AlbumCount)</small>
			</h3>
			<div id="newAlbums">
				@AlbumHelpers.AlbumThumbs(Model.LatestAlbums)
			</div>
		}

		@if (Model.TopAlbums.Any()) {
			<h3 class="withMargin">
				@Html.ActionLink(Res.TopAlbums, "Index", "Search", new { searchType = EntryType.Album, artistId = Model.Id, sort = AlbumSortRule.RatingTotal }, null)
				<small>(@string.Format(Res.RatedAlbums, Model.SharedStats.RatedAlbumCount))</small>
			</h3>
			<div id="topAlbums">
				@AlbumHelpers.AlbumThumbs(Model.TopAlbums)
			</div>
		}


		@if (Model.LatestSongs.Any()) {
			<br />
			<h3>
				@Html.ActionLink(Res.RecentSongs, "Index", "Search", UrlMapper.Search.Songs(artistId: Model.Id, sort: SongSortRule.PublishDate), null)
				<small>(@string.Format(ViewRes.EntryDetailsStrings.NumTotal, Model.SharedStats.SongCount))</small>
			</h3>
			@SongHelpers.SongGrid(Model.LatestSongs, 2, true, true)
		}

		@if (Model.TopSongs.Any()) {
			<br />
			<h3>
				@Html.ActionLink(Res.TopSongs, "Index", "Search", UrlMapper.Search.Songs(artistId: Model.Id, sort: SongSortRule.RatingScore), null)
				<small>(@string.Format(Res.RatedSongsTotal, Model.SharedStats.RatedSongCount))</small>
			</h3>
			@SongHelpers.SongGrid(Model.TopSongs, 2, true, true)
		}
		
		@if (Model.LatestEvents.Any()) {
			<h3 class="withMargin">
				@Html.ActionLink(Res.RecentEvents, "Index", "Search", UrlMapper.Search.Events(artistId: Model.Id, sort: EventSortRule.Date), null)
				<small>(@string.Format(ViewRes.EntryDetailsStrings.NumTotal, Model.SharedStats.EventCount))</small>				
			</h3>
			@Helpers.EventThumbs(Model.LatestEvents)
		}

		<div data-bind="visible: songsOverTimeChart">
			<h3 class="withMargin">@Res.SongsPerMonth</h3>
			<div style="width: 100%; max-width: 800px; height: 300px;" data-bind="highcharts: songsOverTimeChart"></div>
		</div>

		@CommentHelpers.LatestCommentsKnockout()

		<p>
			<a href="#" id="viewCommentsLink">@ViewRes.EntryDetailsStrings.ViewAllComments</a>
		</p>

	</div>

	<div id="discussionTab" data-bind="with: comments">
		@CommentHelpers.EditableComments(UserContext.HasPermission(PermissionToken.CreateComments), well: false)
	</div>

	<div id="picturesTab">

		<ul class="thumbs">
			@Helpers.ThumbItem(Url.Action("Picture", "Artist", new { id = Model.Id }),
				Url.Action("PictureThumb", "Artist", new { id = Model.Id }),
				ViewRes.Album.DetailsStrings.CoverPicture)
			@foreach (var pic in Model.Pictures) {
				@Helpers.ThumbItem(Url.EntryPictureFile(pic, ImageSize.Original), Url.EntryPictureFile(pic, ImageSize.Thumb), pic.Name)
			}
		</ul>

	</div>

	@helper AlbumOptions(string viewModel) {
		<div class="clearfix">
			<div class="pull-right">
				@KnockoutHelpers.SearchDropDown("true", viewModel, Translate.AlbumSortRuleNames.ValuesAndNamesStrings)
				<div class="btn-group" data-bind="with: @viewModel">
					<a data-bind="css: { active: viewMode() == 'Details' }, click: function() { viewMode('Details'); }" class="btn btn-nomargin" href="#" title="@Res.ViewModeDetails">
						<i class="icon-list noMargin"></i>
						@Res.ViewModeDetails
					</a>
					<a data-bind="css: { active: viewMode() == 'Tiles' }, click: function() { viewMode('Tiles'); }" class="btn btn-nomargin" href="#" title="@Res.ViewModeTiles">
						<i class="icon-th noMargin"></i>
						@Res.ViewModeTiles
					</a>
				</div>
			</div>
		</div>
}

	<div id="mainAlbumsTab">
		@AlbumOptions("mainAlbumsViewModel")
		<div data-bind="with: mainAlbumsViewModel">
			@{ Html.RenderPartial("Partials/_AlbumSearchList"); }
		</div>
	</div>

	<div id="collaborationAlbumsTab">
		@AlbumOptions("collaborationAlbumsViewModel")
		<div data-bind="with: collaborationAlbumsViewModel">
			@{ Html.RenderPartial("Partials/_AlbumSearchList"); }
		</div>
	</div>

	<div id="songsTab">
		<div class="clearfix">
			<div class="pull-right">
				@KnockoutHelpers.SearchDropDown("true", "songsViewModel", Translate.SongSortRuleNames.ValuesAndNamesStrings)
				<div class="btn-group" data-bind="with: songsViewModel">
					<a data-bind="css: { active: viewMode() == 'Details' }, click: function() { viewMode('Details'); }" class="btn btn-nomargin" href="#" title="@Res.ViewModeDetails">
						<i class="icon-th-list noMargin"></i>
						@Res.ViewModeDetails
					</a>
					<a data-bind="css: { active: viewMode() == 'PlayList' }, click: function() { viewMode('PlayList'); }" class="btn btn-nomargin" href="#" title="@Res.ViewModePlayList">
						<i class="icon-list noMargin"></i>
						@Res.ViewModePlayList
					</a>
				</div>
			</div>
		</div>
		<div data-bind="with: songsViewModel">
			@{ Html.RenderPartial("Partials/_SongSearchList"); }
		</div>
	</div>

	<div id="shareTab">
		<div>
			@ViewRes.EntryDetailsStrings.Link<br />
			<input type="text" value="@url" class="input-large" onclick="this.select();" />
		</div>
		<div>
			<a href="http://daringfireball.net/projects/markdown/">Markdown</a><br />
			<input type="text" value="@VocaDb.Model.Service.Helpers.MarkdownHelper.CreateMarkdownLink(url, Model.Name)" class="input-xxlarge" onclick="this.select();" />
		</div>
	</div>

</div>

<div data-bind="with: tagsEditViewModel">
	@{ Html.RenderPartial("Partials/_TagsEdit"); }
</div>

@EntryDetailsHelpers.ReportEntryPopupKnockout()

@if (Login.IsLoggedIn) {
	Html.RenderPartial("Partials/_CustomizeArtistSubscriptionDialog");
}

@section BodyScripts {
	@Scripts.Render("~/bundles/Artist/Details")
	<script type="text/javascript" src="https://www.youtube.com/iframe_api"></script>
	<script type="text/javascript">

		$(function() {

			moment.locale('@Culture');

			var urlMapper = new vdb.UrlMapper("@Url.Content("~/")");

			var cultureCode = '@UICulture';
			var loggedUserId = @ToJS(UserContext.LoggedUserId);
			var unknownPictureUrl = '@Url.Content("~/Content/unknown.png")';
			var canDeleteAllComments = @ToJS(UserContext.HasPermission(PermissionToken.DeleteComments));

			var repoFactory = new vdb.repositories.RepositoryFactory(urlMapper, @LanguagePreferenceInt, loggedUserId);
			var artistRepo = repoFactory.artistRepository();
			var albumRepository = repoFactory.albumRepository();
			var songRepo = repoFactory.songRepository();
			var resourceRepo = repoFactory.resourceRepository();
			var userRepository = repoFactory.userRepository();
			var pvPlayerElem = $("#pv-player-wrapper")[0];
			var pvPlayersFactory = new vdb.viewModels.pvs.PVPlayersFactory(pvPlayerElem);
			var tagUsages = @Html.Raw(JsonHelpers.Serialize(Model.Tags));
			var latestComments = @ToJS(Model.LatestComments);

			var reportTypes = @ToJS(Translate.ArtistReportTypeNames.Where(r => r.Id != ArtistReportType.OwnershipClaim).Select(r => new {
				r.Id,
				r.Name,
				NotesRequired = ArtistReport.ReportTypesWithRequiredNotes.Contains(r.Id)
			}));

			var viewModel = new vdb.viewModels.ArtistDetailsViewModel(artistRepo, @Model.Id,
				tagUsages,
				@ToJS(Model.IsAdded),
				@ToJS(Model.EmailNotifications), @ToJS(Model.SiteNotifications),
				@ToJS(Model.Description.HasEnglish),
				unknownPictureUrl,
				@LanguagePreferenceInt,
				urlMapper, albumRepository, songRepo, resourceRepo, userRepository, cultureCode,
				reportTypes,
				loggedUserId,
				canDeleteAllComments,
				pvPlayersFactory,
				latestComments);
			ko.applyBindings(viewModel);

			vdb.views.artist.initPage(@Model.Id, "@ViewRes.SharedStrings.Save", urlMapper, viewModel);

		});

	</script>
}